import django_filters
from main.filters import NumberInFilter
from main.models import Order
from main.permissions import DjangoModelFullPermissions
from rest_framework import serializers, viewsets


class OrderSerializer(serializers.ModelSerializer):
    client = serializers.PrimaryKeyRelatedField(read_only=True, required=False)
    tasks = serializers.SerializerMethodField(read_only=True, required=False)

    def get_tasks(self, obj):
        return obj.tasks.count()

    class Meta:
        model = Order
        fields = (
            "id",
            "number_in_program",
            "send_on_fabric_date",
            "manufacturing_date",
            "delivery_date",
            "status",
            "note",
            "created_on",
            "updated_on",
            "client",
            "tasks",
        )


class OrderFilter(django_filters.FilterSet):
    ids = NumberInFilter(field_name="id", lookup_expr="in")

    class Meta:
        model = Order
        fields = ("id",)


class OrderViewSet(viewsets.ModelViewSet):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer
    permission_classes = (DjangoModelFullPermissions,)
    filterset_class = OrderFilter
